import { defineStore } from "pinia";
import { login, userInfo } from "@/api/api";
import router from "@/router";
import { ElMessage } from 'element-plus'
export const useUserStore = defineStore("store", {
  state() {
    return {
      /**用户信息 */
      userInfo: {},
      /**token */
      token: undefined,
    };
  },
  actions: {
    async login(payload) {
      const LoginRes = await login(payload);
      if (LoginRes.code === 200) {
        this.token = LoginRes.data;
        const UserInfoRes = await userInfo();
        this.userInfo = UserInfoRes.data;
        router.push("/");
        ElMessage({
          message: '登陆成功',
          type: 'success',
          plain: true,
        })
      } else {
        ElMessage({
          message: LoginRes.msg,
          type: 'error',
          plain: true,
        })
      }
    },
    logout() {
      this.$reset()
      router.push("/login");
    }
  },
  persist: {
    paths: undefined,
    key: "__piniaKey__user",
    storage: localStorage,
  },
});
